package com.neihanduanzi.fragment;


import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.neihanduanzi.R;
import com.neihanduanzi.adapter.RecommendListAdapter;
import com.neihanduanzi.api.RecommendService;
import com.neihanduanzi.database.DButil;
import com.neihanduanzi.database.RecommendDb;
import com.neihanduanzi.model.RecommendBean;
import com.neihanduanzi.utils.JsonUtil;

import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class ZTuijianFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = "ZTuijianFragment";
    private List<RecommendBean> mRecommendBeanList;
    private RecommendListAdapter mAdapter;
    private SwipeRefreshLayout mRefreshLayout;

    public ZTuijianFragment() {
        // Required empty public constructor
    }

    @Override
    public String getFragmentTitle() {
        return "推荐";
    }




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View ret = inflater.inflate(R.layout.fragment_ztuijian, container, false);
        RecyclerView recyclerView = (RecyclerView) ret.findViewById(R.id.recommend_list);
        if (recyclerView != null) {
            // TODO: 2016/10/10 创建和设置RecyclerView的Adapter
            //设置 布局管理器，对item排版
            final LinearLayoutManager lm = new LinearLayoutManager(getContext(),
                    LinearLayoutManager.VERTICAL,
                    false);//true  从后往前排
            recyclerView.setLayoutManager(lm);
            recyclerView.setAdapter(mAdapter);
            recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    outRect.set(20,14,20,14);
                }
            });
        }
        initData();
        mRefreshLayout = ((SwipeRefreshLayout) ret.findViewById(R.id.recommend_refresh));
        mRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.pink));
        mRefreshLayout.setOnRefreshListener(this);
        return ret;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mRecommendBeanList = new ArrayList<>();
        initDatabase();
        mAdapter = new RecommendListAdapter(getContext(),mRecommendBeanList);
        x.view().inject(getActivity());
    }

    private void initDatabase() {
        List<RecommendDb> list1 = DButil.queryAllRecommend();
        if (list1 != null) {
            Gson gson = new Gson();
            for (RecommendDb recommendDb : list1) {
                Log.d(TAG, list1.size()+"initDatabase: "+ recommendDb.getRecommendGroup());
                String group = recommendDb.getRecommendGroup();
                RecommendBean recommendBean = gson.fromJson(group, RecommendBean.class);
                mRecommendBeanList.add(recommendBean);
            }
        }
    }


    private void initData() {
        Retrofit.Builder builder=new Retrofit.Builder();
        builder.addConverterFactory(ScalarsConverterFactory.create());
        builder.baseUrl("http://ic.snssdk.com/neihan/stream/mix/v1/");
        Retrofit build = builder.build();
        RecommendService recommendService = build.create(RecommendService.class);

        Call<String> call = recommendService.getRecommendData();
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                    mRefreshLayout.setRefreshing(false);
                    String body = response.body();
                    List<RecommendBean> list = JsonUtil.getDataFromJson(body);
                    mRecommendBeanList.clear();
                    mRecommendBeanList.addAll(list);
                    mAdapter.notifyDataSetChanged();

                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
//                Toast.makeText(getContext(), "网络错误!", Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void onRefresh() {
        initData();
    }
}
